package com.anyext.storage.util.template;

import java.util.List;
import java.util.Map;

import com.anyext.storage.RouterHolder;
import com.anyext.storage.StorageContext;
import com.anyext.storage.mapping.Attribute;
import com.anyext.storage.mapping.Business;
import com.anyext.storage.router.Router;
import com.anyext.storage.util.StringUtils;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class MappingName implements TemplateMethodModel {

	private Map<String, String>	paramAlias;

	public MappingName(Map<String, String> businessAlias) {
		this.paramAlias = businessAlias;
	}

	/**
	 * ${mn('alias')}
	 */
	@Override
	public TemplateModel exec(@SuppressWarnings("rawtypes") List params) throws TemplateModelException {
		String param = String.valueOf(params.get(0));
		String[] alias = StringUtils.DECOLLATOR.split(param);
		String businessName = this.paramAlias.get(alias[0]);
		Business business = StorageContext.getBusiness(businessName);
		if (alias.length == 1) {
			Router router = business.getRouter();
			Map<String, Object> condition = RouterHolder.getTableCondition();
			Object value = condition.get(alias[0]);
			return new SimpleScalar(router.doRoute(value));
		} else {
			Attribute attribute = business.getAttribute(alias[1]);
			return new SimpleScalar(attribute.getColumn());
		}
	}

}
